package com.sxfq.loansupermarket.backsystem.modular.IntegralMall.controller;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.service.IntegralMallLoginService;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.service.MemberProductService;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.service.IGetCacheListService;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.ScoreDealInfo;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.VipLevelInfo;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.CaseInfo;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.DoctorDiagnosisInfo;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.ToothSite;
import com.sxfq.loansupermarket.backsystem.modular.guestDimension.service.IGuestDimensionService;
import com.sxfq.loansupermarket.backsystem.modular.weixin.entity.MedicalAdviceInfo;
import com.sxfq.loansupermarket.backsystem.modular.weixin.entity.SatisfactionSurvey;
import com.sxfq.loansupermarket.backsystem.modular.weixin.service.IWxService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 积分登录控制器
 *
 * @author fengshuonan
 * @Date 2017年1月10日 下午8:25:24
 */
@Controller
@RequestMapping("/integralMallWeixin")
public class IntegralMallLoginController extends BaseController {
    @Autowired
    private MemberProductService service;

    @Autowired
    private IGetCacheListService getCacheListService;

    @Autowired
    private IWxService wxService;

    @Autowired
    private IntegralMallLoginService integralMallLoginService;

    private String PREFIX = "/integralMall/";

    private String PREFIY = "/arrival/customer/";


    /**
     * 跳转到登录
     */
    @RequestMapping(value = "/logincus", method = RequestMethod.GET)
    public String login_cus(Model model) {
        if (ShiroKit.getSessionAttr("reservationsId") == null) {
            model.addAttribute("tabId", 1);
            return PREFIX + "login_cus.html";
        } else {
            ShiroKit.setSessionAttr("reservationsId", null);
            ShiroKit.setSessionAttr("integralRecord", null);
            ShiroKit.setSessionAttr("doctorAdviceList", null);
            model.addAttribute("reservationsId", ShiroKit.getSessionAttr("reservationsId"));
            return PREFIX + "index_cus.html";
        }
    }

    //得到子集
    @RequestMapping(value = "/member/checkin", method = RequestMethod.POST)
    @ResponseBody
    public String checkin(String memberid, String avater, String feature, String shopid, HttpServletResponse response) {
        return "0";
    }

    //修改获取到的门店ip
    @RequestMapping(value = "/updateConfigIp", method = RequestMethod.POST)
    @ResponseBody
    public int updateConfigIp(int shopid, String deptip) {
        return service.updateConfigIp(shopid, deptip);
    }

    //查询门店ip
    @RequestMapping(value = "/queryDeptIpByid", method = RequestMethod.POST)
    @ResponseBody
    public String queryDeptIpByid(String shopid) {
        return service.queryDeptIpByid(shopid);
    }

    //插入到会员到店
    @RequestMapping(value = "/insertMembertable", method = RequestMethod.POST)
    @ResponseBody
    public int insertMembertable(String abbreviation, MembersArriveInfo membersArriveInfo) {
        return service.insertMembertable(abbreviation, membersArriveInfo);
    }

    /**
     * 扫码跳转
     */
    @RequestMapping(value = "/generateQrCode/{id}")
    public String generateQrCode(String id, Model model) {
        model.addAttribute("imgName", "https://pynnn.oss-cn-hangzhou.aliyuncs.com/yiyagzh.jpg");
        model.addAttribute("customerId", id);
        return PREFIY + "generateQrCode.html";
    }

    /**
     * 扫码跳转
     */
    @RequestMapping(value = "/generateQrCodes", method = RequestMethod.POST)
    @ResponseBody
    public int generateQrCode(String id, String code) {
        return integralMallLoginService.generateQrCode(id, code);
    }

    //同步会员接口
    @RequestMapping(value = "/memberSync", method = RequestMethod.GET)
    @ResponseBody
    public List<MembersDistinguishInfo> memberSync() {
        return service.memberSync();
    }

    //更新会员特征码清晰度
    @RequestMapping(value = "/updateMemberFeature", method = RequestMethod.POST)
    @ResponseBody
    public int updateMemberFeature(String reservationsId, String feature, String quality) {
        return service.updateMemberFeature(reservationsId, feature, quality);
    }

    @RequestMapping("/UrlRedirect")
    @ResponseBody
    public Object UrlRedirect() {
        String ticket = "";
        String access_token = getAccessToken();
        com.alibaba.fastjson.JSONObject jsonObject = wxService.qrCodeCreateTmpTicket(access_token, "");
        if (null != jsonObject) {
            ticket = jsonObject.getString("ticket");
        }
        String url = wxService.qrCodePictureUrl(ticket);
        return "demo20191222";
    }

    //获取素材列表
    @RequestMapping("/getMedia_list")
    @ResponseBody
    public com.alibaba.fastjson.JSONObject getMedia_list() {
        return integralMallLoginService.getMedia_list();
    }

    //获取永久图文素材中的网页端URL
    @RequestMapping("/getPermanent_media_url")
    @ResponseBody
    public String getPermanent_media_url() {
        return integralMallLoginService.getPermanent_media_url();
    }

    /**
     * @return
     * @description 微信公众号服务器配置校验token
     * @author: liyinlong
     * @date 2019-05-09 9:38
     */
    @ApiOperation("微信公众号服务器配置校验token")
    @RequestMapping("/checkToken")
    public String parseXml(HttpServletRequest request, HttpServletResponse response) throws Exception {
        integralMallLoginService.checkToken(request, response);
        integralMallLoginService.createMembersUser(request, response);
        return "/1";
    }

    public String getAccessToken() {
        return integralMallLoginService.getAccessToken();
    }

    /**
     * 登录
     */
    @RequestMapping(value = "/loginTo", method = RequestMethod.POST)
    @ResponseBody
    public int loginTo(String userName) {
        return integralMallLoginService.loginTo(userName);
    }

    /**
     * 登录
     */
    @RequestMapping(value = "/getVipLevelName", method = RequestMethod.POST)
    @ResponseBody
    public String getVipLevelName(String reservationsId) {
        return service.getVipLevelName(reservationsId);
    }

    /**
     * 跳转到医嘱列表页面
     */
    @RequestMapping(value = "/doctorAdvice")
    public String treatment(Model model) {
        if (ShiroKit.getSessionAttr("reservationsId") == null) {
            model.addAttribute("tabId", 1);
            return PREFIX + "login_cus.html";
        }
        if (ShiroKit.getSessionAttr("doctorAdviceList") == null) {
            List<DoctorDiagnosisInfo> doctorAdviceList = getCacheListService.getDoctorAdviceList();
            ShiroKit.setSessionAttr("doctorAdviceList", doctorAdviceList);
        }
        model.addAttribute("reservationsId", ShiroKit.getSessionAttr("reservationsId"));//会员ID
        model.addAttribute("doctorAdviceList", ShiroKit.getSessionAttr("doctorAdviceList"));//医嘱列表
        return PREFIX + "doctor_advice.html";
    }

    /**
     * 跳转到积分记录页面
     */
    @RequestMapping(value = "/scoreRecord")
    public String scoreRecord(Model model) {
        if (ShiroKit.getSessionAttr("reservationsId") == null) {
            model.addAttribute("tabId", 1);
            return PREFIX + "login_cus.html";
        }
        List<ScoreDealInfo> scorelist = getCacheListService.getScoreRecord();
        model.addAttribute("reservationsId", ShiroKit.getSessionAttr("reservationsId"));//会员ID
        model.addAttribute("scorelist", scorelist);//积分记录
        return PREFIX + "score_record.html";
    }

    /**
     * 跳转到医嘱列表页面
     */
    @RequestMapping(value = "/integralPushMessage/{medicalAdviceTitle}")
    public String integralPushMessage(@PathVariable String medicalAdviceTitle, Model model) {
        if (ShiroKit.getSessionAttr(medicalAdviceTitle + "medicalAdviceInfo") == null) {
            MedicalAdviceInfo medicalAdviceInfo = getCacheListService.getMedicalAdviceInfo(medicalAdviceTitle);
            ShiroKit.setSessionAttr(medicalAdviceTitle + "medicalAdviceInfo", medicalAdviceInfo);
        }
        model.addAttribute("medicalAdviceInfo", ShiroKit.getSessionAttr(medicalAdviceTitle + "medicalAdviceInfo"));//会员ID
        return PREFIX + "integral_pushMessage.html";
    }

    //跳转到满意度调查
    @RequestMapping(value = "/questionnaire/{openId}/{caseid}")
    public String questionnaire(@PathVariable String openId, @PathVariable String caseid, Model model) {
        model.addAttribute("openId", openId);
        model.addAttribute("caseid", caseid);
        CaseInfo caseInfo=service.questionnaire(caseid);
        if(caseInfo!=null){
            return PREFIX + "questionnaireTwo.html";
        }else{
            return PREFIX + "questionnaire.html";
        }
    }

    /**
     * 跳转到活跃度兑换
     */
    @RequestMapping(value = "/activityLevelTo", method = RequestMethod.GET)
    public String activityLevelTo(Model model) {
        return PREFIX + "activityLevelScore.html";
    }
    @RequestMapping(value = "/activityLevelTwo", method = RequestMethod.GET)
    public String activityLevelTwo(Model model) {
        return PREFIX + "activityLevelScoreTwo.html";
    }
    //跳转到活跃度兑换
    @RequestMapping(value = "/getActivityLevel", method = RequestMethod.POST)
    @ResponseBody
    public MembersUser getActivityLevel(String code) {
        if (code != "" && !code.equals("") && code != null) {
            ShiroKit.setSessionAttr("code", code);
        } else {
            code = ShiroKit.getSessionAttr("code");
        }
        return integralMallLoginService.getActivityLevel(code);
    }
    /**
     * 提交活跃度兑换
     */
    @RequestMapping(value = "/activityLevelAdd", method = RequestMethod.POST)
    @ResponseBody
    public int activityLevelAdd(String openId, String score,String id, Model model) {
        return integralMallLoginService.activityLevelAdd(openId,score,id);
    }
    /**
     * 提交调查问卷
     */
    @RequestMapping(value = "/satisfactionSurveyAdd", method = RequestMethod.POST)
    @ResponseBody
    public int satisfactionSurveyAdd(@RequestBody SatisfactionSurvey ss, Model model) {
        return integralMallLoginService.satisfactionSurveyAdd(ss);
    }

    /**
     * 跳转到个人中心
     */
    @RequestMapping(value = "/personalCenter", method = RequestMethod.GET)
    public String personalCenter(Model model) {
        return PREFIX + "index_cus.html";
    }

    /**
     * 跳转到获取会员推荐ren页面
     */
    @RequestMapping(value = "/memberRecommendation", method = RequestMethod.GET)
    public String memberRecommendation(Model model) {
        if (ShiroKit.getSessionAttr("reservationsId") == null) {
            model.addAttribute("tabId", 1);
            return PREFIX + "login_cus.html";
        }
        model.addAttribute("reservationsId", ShiroKit.getSessionAttr("reservationsId"));//会员ID
        return PREFIX + "member_recommendation.html";
    }

    /**
     * 获取会员推荐ren
     */
    @RequestMapping(value = "/getMemberRecommendation", method = RequestMethod.POST)
    @ResponseBody
    public MemberRecommendationInfo getMemberRecommendation(String code) {
        if (code != "" && !code.equals("") && code != null) {
            ShiroKit.setSessionAttr("code", code);
        } else {
            code = ShiroKit.getSessionAttr("code");
        }
        return integralMallLoginService.getMemberRecommendation(code);
    }

    /**
     * 添加会员推荐人
     */
    @RequestMapping(value = "/sureRecommendation", method = RequestMethod.POST)
    @ResponseBody
    public int sureRecommendation(String recommendationName, String recommendationPhone) {
        return integralMallLoginService.sureRecommendation(recommendationName, recommendationPhone);
    }

    /**
     * 跳转到个人中心
     */
    @RequestMapping(value = "/getPersonalCenter", method = RequestMethod.POST)
    @ResponseBody
    public MembersUser getPersonalCenter(String code) {
        if (code != "" && !code.equals("") && code != null) {
            ShiroKit.setSessionAttr("code", code);
        } else {
            code = ShiroKit.getSessionAttr("code");
        }
        return integralMallLoginService.getPersonalCenter(code);
    }

    /**
     * 分享获取积分
     */
    @RequestMapping(value = "/shareEarnPoints", method = RequestMethod.POST)
    @ResponseBody
    public int shareEarnPoints(String code) {
        if (code != "" && !code.equals("") && code != null) {
            ShiroKit.setSessionAttr("code", code);
        } else {
            code = ShiroKit.getSessionAttr("code");
        }
        return integralMallLoginService.shareEarnPoints(code);
    }

    /**
     * 跳转积分规则
     */
    @RequestMapping(value = "/integralRule", method = RequestMethod.GET)
    public String integralRule(Model model) {
        VipLevelInfo info = getCacheListService.getIntegralRule();
        model.addAttribute("integralRule", info.getIntegralRule());
        model.addAttribute("area", info.getArea().substring(0,7));
        return PREFIX + "integral_rule.html";
    }

    /**
     * 跳转积分记录
     */
    @RequestMapping(value = "/integralRecord/{tabId}", method = RequestMethod.GET)
    public String integralRecord(@PathVariable String tabId, Model model) {
        if (tabId == null) {
            tabId = "1";
        }
        if (ShiroKit.getSessionAttr("reservationsId") == null) {
            model.addAttribute("tabId", tabId);
            return PREFIX + "login_cus.html";
        }
        List<PointRewordInfo> list = getCacheListService.getPointRewordInfoList();
        if (list.size() == 0) {
            return PREFIX + "integral_record_null.html";
        }
        ShiroKit.setSessionAttr("integralRecord", list);
        model.addAttribute("integralRecord", list);
        model.addAttribute("reservationsId", ShiroKit.getSessionAttr("reservationsId"));
        model.addAttribute("tabId", tabId);
        return PREFIX + "integral_record.html";
    }

    @RequestMapping(value = "/verificationCode", method = RequestMethod.POST)
    @ResponseBody
    public String verificationCode(String pid, String reservationsId, String verificationCode, String code) {
        return integralMallLoginService.verificationCode(pid, reservationsId, verificationCode, code);
    }

    @RequestMapping(value = "/to_payServiceConversion/{data}", method = RequestMethod.GET)
    public String to_payServiceConversion(@PathVariable String data, Model model) {
        if (ShiroKit.getSessionAttr("reservationsId") == null) {
            model.addAttribute("tabId", 2);
            return PREFIX + "login_cus.html";
        }
        String pid = data.split(",")[0];
        String reservationsId = data.split(",")[1];
        String code = data.split(",")[2];
        model.addAttribute("pid", pid);
        model.addAttribute("reservationsId", reservationsId);
        model.addAttribute("code", code);
        return PREFIX + "payServiceConversion.html";
    }

    /**
     * 跳转到积分商城武汉
     */
    @RequestMapping(value = "/scoreShopping", method = RequestMethod.GET)
    public String scoreShopping(Model model) {
        return PREFIX + "scoreShopping.html";
    }

    /**
     * 跳转到积分商城恩施
     */
    @RequestMapping(value = "/esScoreShopping", method = RequestMethod.GET)
    public String esScoreShopping(Model model) {
        return PREFIX + "esScoreShopping.html";
    }


    /**
     * 跳转到积分商城
     */
    @RequestMapping(value = "/getScoreShopping", method = RequestMethod.POST)
    @ResponseBody
    public MembersUser getScoreShopping(String code,String area) {
        return integralMallLoginService.getScoreShopping(code,area);
    }

    /**
     * 兑换商品列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object testrInfoList(SearchPointRewordInfo info, HttpServletRequest request) {
        Page<PointRewordInfo> page = new PageFactory<PointRewordInfo>().defaultPage();
        try {
            info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
            info.setLimitIndex(page.getSize());
            page.setCurrent(0);
            List<PointRewordInfo> list = service.selectPageListByQueryGetMap(page, info);
            if (list.size() == 0) {
                info.setStartIndex(0);
                list = service.selectPageListByQueryGetMap(page, info);
            }
            page.setTotal(service.getQueryPagesMemberCount(page, info));
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 跳转到商品详情
     */
    @RequestMapping(value = "/commodityDetails/{id}", method = RequestMethod.GET)
    public String commodityDetails(@PathVariable String id, Model model) {
        if (ShiroKit.getSessionAttr("reservationsId") == null) {
            model.addAttribute("tabId", 2);
            return PREFIX + "login_cus.html";
        }
        PointRewordInfo info = getCacheListService.getPointRewordInfo(id);
        model.addAttribute("id", id);
        model.addAttribute("pointRewordInfo", info);
        model.addAttribute("area", info.getArea().substring(0,7));
        model.addAttribute("reservationsId", ShiroKit.getSessionAttr("reservationsId"));//会员ID
        return PREFIX + "integral_commodityDetails.html";
    }

    /**
     * 跳转到商品兑换
     */
    @RequestMapping(value = "/member_product", method = RequestMethod.GET)
    public String getCustomerProduct(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "memble_product.html";
    }

    /**
     * 跳转到验证码验证
     */
    @RequestMapping(value = "/revision/{ids}", method = RequestMethod.GET)
    public String getRevision(@PathVariable String ids, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String id = ids.split(",")[0];
        String reservationsId = ids.split(",")[1];
        String productId = ids.split(",")[2];
        PointRewordInfo pointRewordInfo = getCacheListService.getIdCodeById(id);
        model.addAttribute("id", id);
        model.addAttribute("productId", productId);
        model.addAttribute("code", pointRewordInfo.getCode());//验证码
        model.addAttribute("reservationsId", reservationsId);
        return PREFIX + "verification_code.html";
    }

    @RequestMapping(value = "/codeNumber", method = RequestMethod.POST)
    @ResponseBody
    public String codeNumber(String code, String codeValue, String id, String reservationsId, String productId) {
        return integralMallLoginService.codeNumber(code, codeValue, id);
    }

    /**
     * 统计查询
     */
    @RequestMapping(value = "/total", method = RequestMethod.GET)
    @ResponseBody
    public List<PointRewordInfo> PointRewordInfototal(String menberStatus, String startCreateTime, String endCreateTime) throws Exception {
        return integralMallLoginService.PointRewordInfototal(startCreateTime, endCreateTime);
    }

    /**
     * 签到的积分
     */
    @RequestMapping(value = "/signInScore", method = RequestMethod.POST)
    @ResponseBody
    public Integer signInScore(String reservationsId, Model model) {
        return integralMallLoginService.signInScore(reservationsId);
    }

    /**
     * 跳转到就诊记录
     */
    @RequestMapping(value = "/getMedicalRecordsInfo", method = RequestMethod.POST)
    @ResponseBody
    public List<CustomerInfo> getMedicalRecordsInfo(String code) {
        return integralMallLoginService.getMedicalRecordsInfo(code);
    }

    /**
     * 跳转到就诊记录
     */
    @RequestMapping(value = "/medicalRecords", method = RequestMethod.GET)
    public String medicalRecords(Model model) {
        return PREFIX + "medicalRecords.html";
    }

    /**
     * 跳转到病例记录
     */
    @RequestMapping(value = "/caseDetails", method = RequestMethod.GET)
    public String caseDetails(Model model) {
        return PREFIX + "caseDetails.html";
    }

    /**
     * 跳转到病例记录
     */
    @RequestMapping(value = "/getCaseDetails", method = RequestMethod.POST)
    @ResponseBody
    public List<CaseInfo> getCaseDetails(String code) {
        return integralMallLoginService.getCaseDetails(code);
    }

    @RequestMapping(value = "/backIntegral", method = RequestMethod.POST)
    @ResponseBody
    public String getBackIntegral(String id, String reservationId) {
        return integralMallLoginService.getBackIntegral(id, reservationId);
    }

    //获取验证码提交
    @RequestMapping(value = "/getMembershipCard", method = RequestMethod.POST)
    @ResponseBody
    public MembersUser getMembershipCard(String membersNum, String phone) {
        return integralMallLoginService.getMembershipCard(membersNum, phone);
    }

    //获取验证码提交
    @RequestMapping(value = "/codeSend", method = RequestMethod.POST)
    @ResponseBody
    public int codeSend(String code, String codeValues, String openId, String customerPhone) {
        return integralMallLoginService.codeSend(code, codeValues, openId, customerPhone);
    }

    //兑换商品
    @RequestMapping(value = "/conversion", method = RequestMethod.POST)
    @ResponseBody
    public String getConversion(String id, String reservationsId) throws ClientException, InterruptedException {
        return integralMallLoginService.getConversion(id, reservationsId) + "," + SUCCESS;
    }

    //getJsapi_ticket分享监听
    @RequestMapping(value = "/getJsapi_ticket", method = RequestMethod.GET)
    @ResponseBody
    public String getJsapi_ticket() {
        return integralMallLoginService.getJsapi_ticket();
    }

    //getJsapiSign
    @RequestMapping(value = "/getJsapiSign", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> getJsapiSign(String url) {
        return integralMallLoginService.getJsapiSign(url);
    }

    @RequestMapping(value = "/to_jssdktest")
    public String print(Model model) {
        return "/jssdktest.html";
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logOut() {
        ShiroKit.setSessionAttr("reservationsId", null);
        ShiroKit.setSessionAttr("integralRecord", null);
        ShiroKit.setSessionAttr("doctorAdviceList", null);
        return PREFIX + "login_cus.html";
    }

    //获取验证码
    @RequestMapping(value = "/getCode", method = RequestMethod.POST)
    @ResponseBody
    public String getCode(String customerPhone) throws ClientException, InterruptedException {
        return integralMallLoginService.getCode(customerPhone) + "," + SUCCESS;
    }

}
